import Mock from 'mockjs'
import userList from '../user/userList'
import authorityList from '../user/authorityList'
import roleList from '../user/roleList'

// 登录接口
Mock.mock('/api/login', 'post', ({ body }) => {
    let { userName, password } = JSON.parse(body)

    const userList1 = JSON.parse(localStorage.getItem('userList')) || userList
    let item = userList1.filter(v => {
        return v.userName == userName && v.password == password
    })
    if (item && item.length) {
        return {
            code: 200,
            msg: "登录成功",
            token: userName,
            userName: userName,
            name: item[0].name
        }
    } else {
        return {
            code: 400,
            msg: "用户名或者密码错误",
        }
    }
})

// 根据token，获取路由权限 

function treeFilter(tree, ids) {
    // 克隆一个新数组
    let arr = tree.map(node => {
        return { ...node }
    })
    // 利用新数组进行筛选
    return arr.filter(node => {
        if (node.children) {
            // 有children的，继续递归
            node.children = node.children && treeFilter(node.children, ids);
            // 筛选出id在id数组中的那一项
            return ids.includes(node.id) || (node.children && node.children.length);
        }
        else {
            // 没有children 直接筛选出id在id数组中的那一项
            return ids.includes(node.id)
        }
    })
}

Mock.mock('/api/permission', 'get', (res, req) => {

    let userName = sessionStorage.getItem('userName')
    const userList1 = JSON.parse(localStorage.getItem('userList')) || userList

    let item = userList1.filter(v => v.userName == userName)

    const roleList1 = JSON.parse(localStorage.getItem('roleList')) || roleList
    if (item && item.length) {
        let obj = item[0]

        let menu = []//我的权限id数组

        // 从角色列表中找到符合roleId的角色的权限id数组
        roleList1.forEach(v => {
            if (v.id == obj.roleId) {
                menu = v.authorityList
            }
        })
        let s = treeFilter(authorityList, menu)


        return {
            code: 200,
            data: s
        }

    }


})